<template>
  <div class="date-picker-box">
    <el-date-picker
      v-model="current_field"
      :value-format="$util.getDefValue(current_args.value_format, 'yyyy-MM-dd HH:mm:ss')"
      :format="$util.getDefValue(current_args.format, 'yyyy-MM-dd')"
      :type="$util.getDefValue(current_args.date_type, 'date')"
      :editable="false"
      unlink-panels
      range-separator="至"
      :placeholder="$util.getDefValue(current_args.placeholder, '选择日期')"
      :picker-options="dateOptions"
      :start-placeholder="$util.getDefValue(current_args.start_placeholder, '开始日期')"
      :end-placeholder="$util.getDefValue(current_args.end_placeholder, '结束日期')"
      :disabled="disabledValue"
      @change="$emit('update:value', current_field)"
    />
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    args: {
      type: Object,
      required: true,
      default: _ => {
        return {};
      }
    },
    options: {
      type: [Array, Object],
      default: _ => {
        return {};
      }
    }
  },
  data() {
    let timespan = '';
    if (this.$util.isArray(this.value)) {
      const start = this.value[0];
      const end = this.value[1];
      timespan = ['', ''];
      if (start && end) {
        timespan = [new Date(start), new Date(end)]
      }
    } else {
      if (this.value) {
        timespan = new Date(this.value);
      }
    }
    return {
      current_field: timespan,
      current_args: this.args
    };
  },
  computed: {
    disabledValue() {
      if (this.current_args.disabled == '1') {
        return true;
      }

      return null;
    },
    dateOptions() {
      if (this.$util.isObject(this.options)) {
        return this.options;
      }
      return {
        disabledDate: function(time) {
          return time.getTime() + 8.64e7 < Date.now();
        },
        shortcuts: [
          {
            text: '昨天',
            onClick: function(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 8.64e7);
              picker.$emit('pick', date);
            }
          },
          {
            text: '今天',
            onClick: function(picker) {
              picker.$emit('pick', new Date());
            }
          }
        ]
      };
    }
  },
  watch: {
    value: {
      handler(now, old) {
        this.current_field = now;
      }
    }
  }
};
</script>
<style scoped>
.date-picker-box {
  max-width: 600px;
}
</style>
